import { getProfileAPI, loginAPI } from '@/api/user'
import router, { constantRoutes, resetRouter } from '@/router'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { Message } from 'element-ui'

export default {
  namespaced: true,
  state() {
    return {
      token: getToken(),
      userinfo: {},
      routes: constantRoutes

    }
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
      setToken(token)
    },
    REMOVE_TOKEN(state) {
      removeToken()
      state.token = null
    },
    SET_USERINFO(state, userinfo) {
      state.userinfo = userinfo
    },
    SET_ROUTES(state, newRoutes) {
      state.routes = [...constantRoutes, ...newRoutes]
    }
  },
  actions: {
    async login(ctx, { password, username }) {
      const { token } = await loginAPI({ password, username })
      if (token !== undefined && token !== null) {
        ctx.commit('SET_TOKEN', token)
        Message.success('登录成功')
        router.replace('/')
      }
    },
    logout(ctx) {
      ctx.commit('REMOVE_TOKEN')
      resetRouter()
    },
    async getUserInfo(ctx) {
      const res = await getProfileAPI()
      console.log(res)

      ctx.commit('SET_USERINFO', res)
      return res
    }
  }
}
